import subprocess
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import time
from utils import center_window, get_icon_path

class DNSCacheCleaner:
    def __init__(self, parent=None):
        self.window = tk.Toplevel(parent) if parent else tk.Tk()
        self.window.title("网络DNS缓存清理")
        
        center_window(self.window, 400, 450)
        self.window.resizable(False, False)
        self.window.iconbitmap(get_icon_path())
        
        if parent:
            self.window.transient(parent)
            self.window.grab_set()
        
        self.create_widgets()
        
        if not parent:
            self.window.mainloop()

    def create_widgets(self):
        main_frame = ttk.Frame(self.window, padding="10")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 状态显示
        self.status_var = tk.StringVar(value="准备就绪")
        status_label = ttk.Label(main_frame, textvariable=self.status_var, font=('微软雅黑', 9))
        status_label.pack(pady=4)
        
        # 日志显示
        log_frame = ttk.LabelFrame(main_frame, text="操作说明", padding="5")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        
        # 创建只读的说明文本框
        self.info_text = tk.Text(log_frame, height=10, width=45)
        self.info_text.pack(fill=tk.BOTH, expand=True)
        
        initial_text = (
            "\n一键清理将执行以下操作:\n"
            " 1. 释放当前IP地址\n"
            " 2. 重新获取IP地址\n"
            " 3. 清除DNS缓存\n\n"
            "注意事项:\n"
            " - 清理过程中会短暂断网\n"
            " - 建议保存好工作再进行清理\n"
            " - 如果出现问题，可以尝试分步清理\n"
        )
        self.info_text.insert('1.0', initial_text)
        self.info_text.configure(state='disabled')
        
        # 创建操作日志文本框
        self.log_text = tk.Text(log_frame, height=5, width=45)
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.log_text.configure(state='disabled')
        
        # 按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)
        
        # 左侧操作按钮（两行）
        left_frame = ttk.Frame(btn_frame)
        left_frame.pack(side=tk.LEFT, padx=5)
        
        ttk.Button(left_frame, text="刷新IP地址", width=15,
                command=lambda: self.manual_clean('renew')).pack(pady=2)
        ttk.Button(left_frame, text="刷新DNS缓存", width=15,
                command=lambda: self.manual_clean('flushdns')).pack(pady=2)
        
        # 右侧按钮
        right_frame = ttk.Frame(btn_frame)
        right_frame.pack(side=tk.RIGHT, padx=5)
        
        ttk.Button(right_frame, text="一键清理", width=15,
                command=self.start_cleaning).pack(pady=2)
        ttk.Button(right_frame, text="关闭窗口", width=15,
                command=self.window.destroy).pack(pady=2)

    def log(self, message):
        """添加日志"""
        self.log_text.configure(state='normal')
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.log_text.configure(state='disabled')

    def update_status(self, message):
        """更新状态信息"""
        self.status_var.set(message)
        self.window.update_idletasks()

    def manual_clean(self, operation):
        """手动清理指定操作"""
        def run_clean():
            try:
                self.update_status("正在执行...")
                self.log_text.configure(state='normal')
                self.log_text.delete(1.0, tk.END)
                self.log_text.configure(state='disabled')
                
                if operation == 'renew':
                    self.update_status("正在更新IP...")
                    self.log("正在重新获取IP地址...")
                    subprocess.run('ipconfig /renew', shell=True, check=True)
                    self.log("IP地址更新完成")
                    self.update_status("IP更新完成")
                
                elif operation == 'flushdns':
                    self.update_status("正在清除DNS缓存...")
                    self.log("正在清除DNS缓存...")
                    subprocess.run('ipconfig /flushdns', shell=True, check=True)
                    self.log("DNS缓存清除完成")
                    self.update_status("DNS缓存已清除")
                
                messagebox.showinfo("完成", "操作已完成!")
                
            except Exception as e:
                self.update_status("操作失败")
                self.log(f"\n发生错误: {str(e)}")
                messagebox.showerror("错误", f"操作失败:\n{str(e)}")
        
        threading.Thread(target=run_clean, daemon=True).start()

    def start_cleaning(self):
        """开始清理进程"""
        self.log_text.configure(state='normal')
        self.log_text.delete(1.0, tk.END)
        self.log_text.configure(state='disabled')
        threading.Thread(target=self._clean_process, daemon=True).start()

    def _clean_process(self):
        """清理处理过程"""
        try:
            # 1. 释放IP
            self.update_status("正在释放IP...")
            self.log("正在释放IP地址...")
            subprocess.run('ipconfig /release', shell=True, check=True)
            self.log("IP地址释放完成")
            
            # 2. 重新获取IP
            self.update_status("正在更新IP...")
            self.log("正在重新获取IP地址...")
            subprocess.run('ipconfig /renew', shell=True, check=True)
            self.log("IP地址更新完成")
            
            # 3. 清除DNS缓存
            self.update_status("正在清除DNS缓存...")
            self.log("正在清除DNS缓存...")
            subprocess.run('ipconfig /flushdns', shell=True, check=True)
            self.log("DNS缓存清除完成")
            
            # 完成
            self.update_status("清理完成")
            self.log("\n所有操作已完成!")
            messagebox.showinfo("完成", "DNS缓存清理完成!")
            
        except Exception as e:
            self.update_status("发生错误")
            self.log(f"\n发生错误: {str(e)}")
            messagebox.showerror("错误", f"发生未知错误:\n{str(e)}")

if __name__ == "__main__":
    DNSCacheCleaner()